<?php
namespace Admin\Controller;
use Common\Controller\BackendController;

// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.itaoke.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  Caption <Caption@163.com> QQ 1674653
// +----------------------------------------------------------------------

class QuancaijiController extends BackendController {
    public function _initialize() {
        parent::_initialize(); 
        
        $api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
        $this->_tbconfig = unserialize($api_config);
    }
    public function index() {
        $this->display();
    }
    
    public function getUnionCats(){
    	if(!IS_AJAX) return ;
    	$quancats= S('itk_quancats');
    	if(!$quancats){
    		$fields['key']='itaoke_cats';
    		$tb_top = $this->_get_top();
    		$req = $tb_top->load_api('ItaokeCatsRequest');
    		$req->putOtherTextParam( 'key',$fields);				// 设置采集数据分类ID
    		$resp = (array)$tb_top->execute($req); 

    		S('itk_quancats',$resp['data']);
    		$this->ajaxReturn(0,'',$resp['data']);
    	}
		else{
			$this->ajaxReturn(0,'',$quancats);
		}
    }
    
    public function setting() {
        if (IS_POST) {
            $cate_id	= $this->_post('cate_id', 'trim',0);
            $cat		= $this->_post("cat" , "trim",0);
            $num		= $this->_post("num" , "trim");
            $min		= $this->_post("mincommission" , "trim");

//             if (!$cate_id) {
//                 $this->ajaxReturn(0, "入库分类必须选择!");
//             }
            
            if( $this->_tbconfig =='')
            	$this->ajaxReturn(0, "请正确配置爱淘客开放平台接口!");
            
			//把采集信息写入缓存
            F("quancaiji_setting" , array(
                "cate_id" => $cate_id,
                "cat" => $cat,
                "page" => $num,
            	"min" => $min,
            ));
            $this->collect();
        }
    }
    
    public function collect() {
    	
        if (false === $quancaiji_setting = F('quancaiji_setting')) {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }

        $taodianjin = C('itk_taojindian_html');
        if (strpos($taodianjin, "text/javascript")) {
        	$pid = get_word($taodianjin, 'pid: "' , '"');
        } else {
        	$pid = $taodianjin;
        }
        if (!$pid) {
        	$this->ajaxReturn(0, '请设置淘点金后采集！否则无佣金');
        }
        
        $p = I('get.p','1');
        if($p>$quancaiji_setting['page'])
        	$this->ajaxReturn(0, "已经采集完成" . $quancaiji_setting['page'] . "页！请返回，谢谢");
        
        $tb_top = $this->_get_top();
        $req = $tb_top->load_api('ItaokeQuanGetRequest');
        $req->putOtherTextParam('cat',$quancaiji_setting['cat']);				// 设置采集数据分类ID
        $req->putOtherTextParam('page',$p);									// 设置页数
        $req->putOtherTextParam('min',$quancaiji_setting['min']);				// 设置最小佣金
        
        $resp = (array)$tb_top->execute($req);

        if($resp['status'] != '0000')
        {
        	$this->ajaxReturn(0, $resp['msg']);
        }
        else
        {
        	if ($p == 1) {
        		$totalcoll = 0;
        	} else {
        		$totalcoll = F("totalcoll");
        	}
        	
        	$coll = 0;
			$item = $resp['data'];
			$totalnum = count($item);
        	for($i=0;$i<$totalnum;$i++)
        	{
        		$_item['cate_id'] = $item[$i]['cid'];
        		$_item['num_iid'] = $item[$i]['num_iid'];
        		$_item['title'] = $item[$i]['title'];
        		$_item['tags'] = $item[$i]['tags'];
        		$_item['sellerId'] = $item[$i]['sellerid'];
				if(false ===strpos($item[$i]['pic_url'], 'http'))
					$_item['pic_url'] = 'http:'.$item[$i]['pic_url'];
				else
					$_item['pic_url'] = $item[$i]['pic_url'];

        		$_item['price'] = $item[$i]['price'] != '' ? $item[$i]['price'] :$item[$i]['coupon_price'];
        		$_item['volume'] = $item[$i]['sale_num'] == '' ? 0 : $item[$i]['sale_num'];
        		$_item['coupon_price'] = $item[$i]['coupon_price'];
        		$_item['coupon_rate']	= round(($_item['coupon_price']/$_item['price'])*10000, 0);
        		$_item['shop_type'] = $item[$i]['source_id'] == 1 ? 'C':'B';
        		$_item['item_url'] = $item[$i]['item_url'];
        		$_item['add_time'] = time();
        		$_item['isq'] = 1;
        		$_item['quan'] = $item[$i]['qprice'];
        		$_item['quanurl'] = $item[$i]['qwurl'];
        		$_item['quan_surplus'] = $item[$i]['qsnum'];
        		$_item['quan_receive'] = $item[$i]['qnum'] - $item[$i]['qsnum'];
        		$_item['commission_rate'] = $item[$i]['commission'];
        		$_item['nick']='爱淘客联盟';
        		$_item['coupon_start_time']=time();
        		$_item['coupon_end_time']=$item[$i]['qtime']+24*60*60-1;
        		$_item['ems'] = $item[$i]['ems'];
        		$_item['astime'] = date('Ymd');
        		$_item['dx'] = $item[$i]['plan_id'] == 2 ? 1 :0;
        		$_item['intro'] = $item[$i]['content'] ;
				$_item['quan_condition']=$item[$i]['qcon'];
				
        		if(0 != $this->_ajax_tb_publish_insert($_item))
        			$coll++;
        		$totalcoll++;
        	}
//        	if ($coll == 0) {
//        		$this->ajaxReturn(0, "本次更新采集已完成，本页已经采集不重复~");
//        	}

        	F("totalcoll" , $totalcoll);
        	$this->assign('p', $p);								// 采集当前页数
        	$this->assign("coll" , $coll);						// 每页完成个数
        	$this->assign("pages" , $quancaiji_setting['page'] );		// 总页数
        	$this->assign("totalnum" , $totalnum);					// 每页个数
        	$this->assign("totalcoll" , $totalcoll);				// 总个数
        	$resp = $this->fetch("collect");
        	$this->ajaxReturn(1, '', $resp);
        }
    }
    
    private function _ajax_tb_publish_insert($item) {
      return D('Items')->ajax_itk_publish($item);
    }

    private function _get_top() {
    	vendor('Itaoke.TopClient');
    	vendor('Itaoke.RequestCheckUtil');
    	vendor('Itaoke.Logger');
    	$top = new \TopClient;
    	$top->appkey = $this->_tbconfig['app_key'];
    	$top->secretKey = $this->_tbconfig['app_secret'];
    	return $top;
    }
} 
?>
